package org.spring.springboot.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: eric
 * Date: 2017-12-20
 * Time: 20:27
 */
public class DateUtil {

    private static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public static int zoneDays(Date date1, Date date2) {
        //相同日期算一天
        return differentDays(date1, date2) + 1;
    }

    public static String zoneEndDate(Date date1, int day) {
        //相同日期算一天
        if (day <= 1) {
            return formatDate.format(date1);
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        cal1.add(Calendar.DAY_OF_YEAR, (day - 1));
        return formatDate.format(cal1.getTime());
    }


    public static int differentDays(Date date1, Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //不同年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else    //同年
        {
            return day2-day1;
        }
    }

    public  static  Date strToDate(String d){
        if(StringUtils.isBlank(d)){
            return null;
        }
        try {
            return formatDateTime.parse(d);
        } catch (ParseException e) {
            return null;
        }
    }


    public static int daysFrom2000(Date date) {
        String time_base="2000-01-01 00:00:00";
        Date data_base = strToDate(time_base);
        return differentDays(data_base,date);
    }
}
